<?php
/**
 * Created by PhpStorm.
 * User: summercode
 * Date: 2018/12/23
 * Time: 3:45 PM
 */

namespace app\index\controller;


use app\common\controller\BaseModel;
use app\common\model\OrderModel;
use app\common\model\RecodeModel;
use app\common\model\SellerInfoModel;
use app\common\model\SettingModel;
use app\common\model\TicketModel;
use app\common\model\UserModel;
use think\Config;
use think\Request;

class User extends BaseModel
{

    // 构造方法
    public function  __construct(Request $request = null)
    {
        header('Access-Control-Allow-Origin: *');
        parent::__construct($request);
    }

    // 小程序登录接口
    public function login (Request $request) {

        // 获取配置中的appid和secret
        $appid = Config::get('minip.appid');
        $secret = Config::get('minip.secret');

        $js_code = $request->param('code');
        $encryptedData = $request->param('enc');
        $iv = $request->param('iv');

        // 微信接口地址
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$secret."&js_code=".$js_code."&grant_type=authorization_code";
        $data = $this->https_request($url, 'get', 'json', '');
        $data = json_decode($data,true);

        $pc = new \WXBizDataCrypt($appid, $data['session_key']);
        $errCode = $pc->decryptData($encryptedData, $iv, $data2);
        $data2 = json_decode($data2,true);

        $userModel = new UserModel();

        $user = $userModel->where('openId', $data2['openId'])->find();

        if (empty($user)) {
            $res = $userModel->data([
                'openId' => $data2['openId'],
                'avatarUrl' => $data2['avatarUrl'],
                'gender' => $data2['gender'],
                'nickName' => $data2 ['nickName']
            ])->save();

            if ($res > 0) {

                $user = $userModel->where('openId', $data2['openId'])->find();

                return $this->json_data(1, '000000', '恭喜用户注册成功', $user, '');
            }
        }

        return $this->json_data(1, '000000', '登录成功', $user, '');
    }


    // 小程序获取用户手机

    public function getUserPhone(Request $request) {

        // 获取配置中的appid和secret
        $appid = Config::get('minip.appid');
        $secret = Config::get('minip.secret');

        $js_code = $request->param('code');
        $encryptedData = $request->param('enc');
        $iv = $request->param('iv');

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$secret."&js_code=".$js_code."&grant_type=authorization_code";
        $data = $this->https_request($url, 'get', 'json', '');

        $data = json_decode($data,true);

        $pc = new \WXBizDataCrypt($appid, $data['session_key']);
        $errCode = $pc->decryptData($encryptedData, $iv, $data2);
        $data2 = json_decode($data2,true);


//        $userModel = new UserModel();
//
//        $res = $userModel->where('id', $uid)->update(['phone' => $data2['phoneNumber']]);
//
//        if ($res > 0) {
//            return $this->json_data(1, '000000', '手机绑定成功', $data2, '');
//        }

        return $this->json_data(0, '000000', '手机号', $data2['phoneNumber'], '');
    }



    // 是否拥有抢券资格
    public function isGrabTicket(Request $request) {

        // 获取用户ID，查看用户是否已经抢过券
        $uid = $request->param('uid');

        if (empty($uid)) {
            return $this->json_data(1, '000001', '请传入UID', '', '');
        }

        $user = new UserModel();
        $setting = new SettingModel();


        $ticketNum = $setting->where('jack_key', 'ticket')->value('jack_value');

        $start_time = $setting->where('jack_key', 'start_time')->value('jack_value');
        $end_time = $setting->where('jack_key', 'end_time')->value('jack_value');

        $now = time();

        if ($start_time > $now) {
            return $this->json_data(1, '900002', '活动未开始', '', '');
        }

        if ($end_time < $now) {
            return $this->json_data(1, '900002', '活动已开始', '', '');
        }

        if ($ticketNum <= 0) {

            $status = $user->where('id', $uid)->value('status');

            if ($status == 0) {
                $count = $user->where('id', $uid)->value('count');
                $user->where('id', $uid)->update([
                    'status' => -1,
                    'count' => ++$count
                ]);
            }
            return $this->json_data(1, '900001', '券已抢完', '', '');

        }

        $is_ticket = $user->where('id', $uid)->value('is_ticket');

        if ($is_ticket == 1) {
            return $this->json_data(1, '400001', '用户已抢券', '', '');
        }

        if ($is_ticket == 0) {
            return $this->json_data(0, '000000', '用户可以抢券', '', '');
        }
    }


    // 提交订单并创建卡券

    /**
     * @param Request $request
     * @return \think\response\Json
     * @throws \Exception
     *
     *  todo 执行完成后修改活动的配置表中的活动礼包数量
     */
    public function grabTicket(Request $request) {
        // 提交用户ID
        $uid = $request->param('uid');

        $userModel = new UserModel();
        $orderModel = new OrderModel();
        $ticketModel = new TicketModel();
        $setting = new SettingModel();

        $is_ticket = $userModel->where('id', $uid)->value('is_ticket');

        if ($is_ticket == 1) {
            return $this->json_data(1, '400001', '用户已抢券，订单不合法。', '', '');
        }

        $orderData = [
            'uid' => $uid,
            'order_id' => BaseModel::createOID(),
            'price' => 9.8
        ];

        $res = $orderModel->data($orderData)->save();

        $oid = $orderModel->id;
        // 如果创建订单成功
        if ($res == 1) {

            // 现金红包1个插入奖池
            $setting = new SettingModel();

            // 获取奖池
            $prizeStr = $setting->where('jack_key', 'prizeArr')->value('jack_value');

            // 奖池字符串转化为数组
            $prizeArr = explode(',', $prizeStr);

            array_push($prizeArr, mt_rand(6000, 6999));
            // 打乱数组
            shuffle($prizeArr);

            // 将打乱的数组再次转化为字符串存入数据库中
            $longText = implode(",", $prizeArr);
            $setting->where('jack_key', 'prizeArr')->update([
                'jack_value' => $longText
            ]);

            //  创建3张A5抵购券
            $arr = array();
            for ($i = 0; $i < 3; $i++) {

                $t1 = [
                    'uid' => $uid,
                    'oid' => $oid,
                    'tname' => '100元A5专用抵价券',
                    'tprice' => 100,
                    'is_all' => 0,
                    'is_pass' => 0,
                    'validate' => 1554047980,
                    't_class' => 1
                ];

                array_push($arr, $t1);

            }


            //  创建2张通用抵购券
            for ($j = 0; $j < 2; $j++) {

                $t2 = [
                    'uid' => $uid,
                    'oid' => $oid,
                    'tname' => '100元通用抵价券',
                    'tprice' => 100,
                    'is_all' => 1,
                    'is_pass' => 0,
                    'validate' => 1554047980,
                    't_class' => 1
                ];

                array_push($arr, $t2);

            }

            $ticketModel->saveAll($arr);

            // 修改用户是否有权抢券字段
            $userModel->where('id', $uid)->update(['is_ticket' => 1, 'status' => 1]);
        }

        //

        if ($res == 0) {
            return $this->json_data(0, '400002', '订单未创建', '', '');
        }

        $ticketNum = $setting->where('jack_key', 'ticket')->value('jack_value');
        $setting->where('jack_key', 'ticket')->update([
            'jack_value' => --$ticketNum
        ]);

        return $this->json_data(0, '000000', '订单创建成功', '', '');

    }


    // 用户查看自己的抵价券列表


    public function ticketList(Request $request) {
        // 提交用户ID
        $uid = $request->param('uid');
        $type = $request->param('type') ? $request->param('type') : 0;

        if (empty($uid)) {
            return $this->json_data(1, '000001', '请传入UID', '', '');
        }

        $ticketModel = new TicketModel();

        $res = $ticketModel->where('uid', $uid)->where('is_check', $type)->select();

        return $this->json_data(0, '000000', '我的订单', $res, '');
    }



    public function ticketDetail(Request $request) {
        // 提交用户ID
        $qid = $request->param('qid');

        if (empty($qid)) {
            return $this->json_data(1, '000003', '请传入qid', '', '');
        }

        $ticketModel = new TicketModel();
        $userModel = new UserModel();

        $ticket = $ticketModel->where('id', $qid)->find();

        if (!$ticket['qr_address']) {

            $savePath = 'qrcode/';
            $webPath = '/qrcode/';
            $qrData = 'qid='.$ticket['id'].'&'.'uid='.$ticket['uid'].'&'.'oid='.$ticket['oid'];
            $qrLevel = 'H';
            $qrSize = '8';
            $savePrefix = 'NickBai';

            if($filename = $this->createQRcode($savePath, $qrData, $qrLevel, $qrSize, $savePrefix)){
                $pic = $webPath . $filename;
            }
            $ticketModel->where('id', $qid)->update([
                'qr_address' => $pic
            ]);

            $ticket = $ticketModel->where('id', $qid)->find();

        }

        $uid = $ticket['uid'];
        $ticket['qr_address'] = 'https://market.jackgroup.cn' . $ticket['qr_address'];
        $ticket['userinfo'] = $userModel->where('id', $uid)->find();

        return $this->json_data(0, '000000', '我的订单详情', $ticket, '');


    }

    /**
     *
     * 获取区域area
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function areaSeller(Request $request) {

        $area = $request->param('area');

        $sellerInfo = new SellerInfoModel();

//        $data = $sellerInfo->where('area', 'like', '%'.substr($area,0,strlen($area)-3).'%')->select();
//        $data = $sellerInfo->where('area', 'like', '%'. $area .'%')->select();
        $data = $sellerInfo->where('city', 'like', '%'. $area .'%')->select();

        return $this->json_data(0, '000000', '我附近的门店', $data, '');
    }



    public function userInfoByUid(Request $request) {

        $uid = $request->param('uid');

        if (empty($uid)) {
            return $this->json_data(0, '200001', '缺少用户ID', '', '');

        }

        $user = new UserModel();

        $data = $user->where('id', $uid)->find();


        if ($data) {
            return $this->json_data(0, '000000', '用户信息', $data, '');
        } else {
            return $this->json_data(0, '400001', '未知用户', $data, '');

        }

    }

    // 返回活动配置信息
    public function activeConfig() {
        $setting = new SettingModel();

        $start_time = $setting->where('jack_key', 'start_time')->value('jack_value');
        $end_time = $setting->where('jack_key', 'end_time')->value('jack_value');

        $ticket_num = $setting->where('jack_key', 'ticket')->value('jack_value');

        $now = time();

        if ($start_time < $now && $end_time > $now) {
            return $this->json_data(1, '000000', '', [
                'start_time' => $start_time,
                'end_time' => $end_time,
                'ticket_num' => $ticket_num,
                'times' => $end_time - $now
            ], '');
        }

        if ($start_time > $now) {
            return $this->json_data(0, '700001', '活动未开启', '', '');
        }

        if ($end_time < $now) {
            return $this->json_data(0, '700002', '活动已结束', '', '');
        }

    }


    public function recodeString(Request $request) {
        $recode = new RecodeModel();
        $user = new UserModel();

        $page = $request->param('page') ? $request->param('page') : 1;
        $num = $request->param('num') ? $request->param('num') : 10;

        $data = $recode
            ->limit(($page - 1) * $num, $num)
            ->order('update_time', 'desc')
            ->select();

        $result = array();

        foreach ($data as $item) {
            $userData = $user->where('id', $item['uid'])->find();

            $item['user'] = $userData;

            array_push($result, $item);
        }

        $str = '';
        for ($i = 0; $i < count($result); $i++) {
            $str .= '恭喜用户：'.$result[$i]['user']['nickName'] . '获得：' . $result[0]['content']. '  ----';
        }

        return $this->json_data(1, '000000', '中奖字符串', $str, '');

    }

    public function getUserLocation(Request $request) {

        $lat = $request->param('lat');
        $lng = $request->param('lng');

        $data = $this->https_request('https://apis.map.qq.com/ws/geocoder/v1/?location='.$lat.','.$lng.'&key=B3EBZ-EJVKU-UELVJ-43WTN-2DHQH-S5F3Q&get_poi=0', 'get', 'json');

        $data = json_decode($data,true);
        return $this->json_data(1, '000000', '位置详情', $data, '');
    }




}